import { Component, OnInit, ViewChild, HostListener } from '@angular/core';
import { Helper } from '../common/index';
import { ControlBase } from '../../shared/dynamicform/controlbase';
import { TextBox } from '../../shared/dynamicform/textbox-control';
import { EmailValidator } from '../../shared/dynamicform/my-validator';
import { FormGroup, Validators } from '@angular/forms';
import { Observable } from 'rxjs/Rx';
import { SessionService } from '../../services/session-service';
import { AuthService } from '../../services/auth-service';
import { MdlAlertComponent } from '@angular-mdl/core';
import { Router } from '@angular/router';
import { Location } from '@angular/common';
@Component({
    selector: 'app-login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.scss'],
    providers: [AuthService, SessionService]
})
export class LoginComponent implements OnInit {
    formInputs: ControlBase<any>[];

    formControls: any;

    isSubmit: boolean = false;

    @ViewChild('loginForm') loginForm;

    @ViewChild('failAlert') alert;

    redirectPage: { [role: string]: string } = {
        1: '/project',
        2: '/property',
        3: '/user',
        4: '/visit'
    };
    constructor(
        private _router: Router,
        private _authService: AuthService,
        private _sessionService: SessionService,
        private _location: Location
    ) {}

    ngOnInit() {
        if (this._sessionService.isAuth()) {
            this._location.back();
        }
        this.formControls = this._setForm(null);
    }

    private _setForm(data: any): any {
        this.formInputs = [
            new TextBox({
                type: 'text',
                key: 'email',
                label: '手机号/邮箱',
                value: data ? data.userName : '',
                required: true,
                order: 0,
                groupId: 0,
                validators: Validators.required
            }),
            new TextBox({
                type: 'password',
                key: 'password',
                label: '密码',
                value: data ? data.password : '',
                required: true,
                order: 1,
                groupId: 1,
                require: true,
                validators: Validators.required
            })
        ];
        return Helper.setGroupForm(this.formInputs);
    }
    async login(df: any) {
        this.isSubmit = true;
        const form = <FormGroup>df.form;
        if (!form.valid) {
            return false;
        }
        const formVal = this.loginForm.form.value;
        try {
            const data = await this._authService
                .login({
                    email: formVal.email,
                    password: formVal.password
                })
                .toPromise();
            const body: any = data;
            this._sessionService.create(body.token, body.user);
            const roles = this._sessionService.getRoles();
            // const path = this.redirectPage[
            //     (roles[0].roleName as string).toLowerCase()
            // ];
            const path = this.redirectPage[roles[0].id];
            location.replace(path.toString());
            // this._router.navigate(['/project']);
        } catch (e) {
            console.log(e);
            this.alert.show();
        } finally {
            this.isSubmit = false;
        }
    }
    @HostListener('keydown.enter')
    submit() {
        this.login(this.loginForm);
    }
    public onLoadFormData(form) {
        console.log(form);
    }
}
